using System;
using System.Collections.Generic;
using System.Text;
using NobleTech.Products.CreatureKingdom.Utils;

namespace NobleTech.Products.CreatureKingdom
{
    internal class TopQuadrant : IQuadrant
    {
        private IQuadrant childQuadrant;

        public TopQuadrant(RectangleD area)
        {
            this.childQuadrant = new Quadrant(area, this);
        }

        public ViewPort GetViewPort(RectangleD bounds)
        {
            return new ViewPort(bounds, childQuadrant);
        }

        public IEnumerable<Organism> GetAllOrganisms()
        {
            return GetContainedOrganisms(Area, 0);
        }

        public RectangleD Area { get { return childQuadrant.Area; } }

        public bool IsEmpty { get { return childQuadrant.IsEmpty; } }

        public Organism LargestOrganism { get { return childQuadrant.LargestOrganism; } }

        public IEnumerable<Organism> GetContainedOrganisms(RectangleD bounds, double minSize)
        {
            return childQuadrant.GetContainedOrganisms(bounds, minSize);
        }

        public void AddOrganism(Organism organism)
        {
            while (!Area.Contains(organism.Location))
                // Create a new Quadrant extended out in the direction of the organism
                childQuadrant = childQuadrant.Extend(organism.Location);
            childQuadrant.AddOrganism(organism);
        }

        public Organism RemoveLargestOrganism()
        {
            return childQuadrant.RemoveLargestOrganism();
        }

        public IQuadrant GetSmallestQuadrantContaining(RectangleD bounds)
        {
            if (Area.Contains(bounds))
                return childQuadrant.GetSmallestQuadrantContaining(bounds);
            return this;
        }

        public IQuadrant Extend(PointD towards)
        {
            throw new InvalidOperationException("Attempt to Extend a TopQuadrant");
        }

        #region Turn Steps

        public void GetMove()
        {
            childQuadrant.GetMove();
        }

        public void UpdateInfo()
        {
            childQuadrant.UpdateInfo();
        }

        public void DoInteraction()
        {
            childQuadrant.DoInteraction();
        }

        public void DoMove()
        {
            childQuadrant.DoMove();
        }

        public void DoLifeEvents()
        {
            childQuadrant.DoLifeEvents();
        }

        #endregion

        public event ChildQuadrantEventHandler OrganismGrown;
    }
}
